package com.zjw.algorithm.ready1;

public class _最长交替子数组 {

    public static void main(String[] args) {
        System.out.println(new _最长交替子数组().alternatingSubarray(new int[]{14, 30, 29, 49, 3, 23, 44, 21, 26, 52}));
    }

    public int alternatingSubarray(int[] nums) {
        if (nums == null || nums.length == 0) {
            return -1;
        }

        int p1 = 1;
        int p2;

        int maxCount = 0;
        for (int i = 1; i < nums.length; i++) {
            int currentMulti = nums[i] - nums[i - 1];
            if (Math.abs(currentMulti) != 1) {
                p2 = 1;
            } else if (p1 == 1) {
                p2 = currentMulti == 1 ? 2 : 1;
            } else {
                int lastMulti = nums[i - 1] - nums[i - 2];
                if (lastMulti * currentMulti < 0) {
                    p2 = p1 + 1;
                } else if (currentMulti == 1) {
                    p2 = 2;
                } else {
                    p2 = 1;
                }
            }
            p1 = p2;
            maxCount = Math.max(maxCount, p2);
        }

        return maxCount == 1 ? -1 : maxCount;
    }
}
